package com.example.lte.service;

import com.example.lte.entity.LoginLogEntity;
import com.example.lte.repo.LoginLogRepo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lzh
 * @date 2020/11/5 - 19:09
 */
@Service
public class LoginLogServiceImpl {


    @Resource
    private LoginLogRepo loginLogRepo;

    public void delByLoginToken(String token){
        loginLogRepo.deleteByReqTokenEquals(token);
    }

    public List<String> getTargetOnlineToday(Long[] ids){
        return loginLogRepo.findDistinctAccountOnlineTodayByUserIds(ids);
    }

    public Page<LoginLogEntity> findByCondition(String account, Date startDate, Date endDate, Pageable pageable){
        return loginLogRepo.findAll((root, query, cb)->{
            List<Predicate> predicates = new ArrayList<>();
            //equal 示例
            if (!StringUtils.isEmpty(account)){
                predicates.add(cb.equal(root.get("account"),account));
            }
            //greaterThan 大于等于示例
            if (startDate!=null){
                predicates.add(cb.greaterThan(root.get("addTime"),startDate));
            }
            //lessThan 小于等于
            if (endDate!=null){
                predicates.add(cb.lessThan(root.get("addTime"),endDate));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        },pageable);
    }



    @Transactional(rollbackFor = Exception.class)
    public void saveLoginLog(LoginLogEntity entity){
        loginLogRepo.save(entity);
    }

}
